package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.ExposureNumResponse;
import com.ytjj.common.model.MyIncomeDataResponse;
import com.ytjj.common.model.MyWalletResponse;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.mall.enums.DynamicExposureTypeEnums;
import com.ytjj.qmyx.mall.enums.UserBalanceSourceEnums;
import com.ytjj.qmyx.mall.mapper.PlatformStrictInfoMapper;
import com.ytjj.qmyx.mall.mapper.PlatformStrictProfitMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.response.PlatformStrictInfoResponse;
import com.ytjj.qmyx.mall.model.response.PlatformStrictListResponse;
import com.ytjj.qmyx.mall.model.response.PlatformStrictProfitItemResponse;
import com.ytjj.qmyx.mall.model.response.PlatformStrictProfitResponse;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.DynamicService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.service.PlatformStrictInfoService;
import com.ytjj.qmyx.mall.utils.DateUtils;
import com.ytjj.qmyx.mall.utils.WeekToDateUtil;
import com.ytjj.qmyx.users.client.AdminClient;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersInfoMapper;
import com.ytjj.qmyx.users.mapper.UsersMapper;
import com.ytjj.qmyx.users.model.DynamicIncomeDto;
import com.ytjj.qmyx.users.model.Users;
import com.ytjj.qmyx.users.model.UsersInfo;
import com.ytjj.qmyx.users.model.UsersInfoExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Service
@RefreshScope
public class PlatformStrictInfoServiceImpl extends BaseController implements PlatformStrictInfoService {
    @Resource
    private PlatformStrictInfoMapper platformStrictInfoMapper;
    @Resource
    private PlatformStrictProfitMapper platformStrictProfitMapper;//收益
    @Resource
    private UsersInfoMapper usersInfoMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private UsersClient usersClient;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private OrdersService ordersService;
    @Resource
    private PlatformStrictMapper appPlatformStrictMapper;
    @Resource
    private PlatformStrictAPPListMapper platformStrictListMapper;
    @Resource
    private AdminClient adminClient;
    @Value("${brokerageRatio:1.6}")
    private String brokerageRatio;
    @Resource
    private DynamicExposureRecordMapper dynamicExposureRecordMapper;
    @Value("${talent-uplineTime:20210727}")
    private String talentUplineTime;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private RedisService redisService;
    @Value("${incomeRankWeekBaseValue:500}")
    private String incomeRankWeekBaseValue;
    @Value("${incomeRankHistoryBaseValue:1000}")
    private String incomeRankHistoryBaseValue;


    /**
     * 查询推荐达人
     * @return
     */
    @Override
    public List<PlatformStrictInfoResponse> recommentTalent(Integer pageSize) {
        PageHelper.startPage(0, pageSize);
        PlatformStrictInfoExample example = new PlatformStrictInfoExample();
        example.setOrderByClause("create_time desc");
        List<PlatformStrictInfo> list = platformStrictInfoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<Integer> usersIdList = list.stream().map(PlatformStrictInfo::getUserId).collect(Collectors.toList());
        UsersInfoExample usersInfoExample = new UsersInfoExample();
        usersInfoExample.createCriteria().andIdIn(usersIdList);
        List<UsersInfo> usersInfoList = usersInfoMapper.selectByExample(usersInfoExample);
        List<PlatformStrictInfoResponse> result = new ArrayList<>();

        List<Integer> productIdList = list.stream().map(PlatformStrictInfo::getProductId).collect(Collectors.toList());
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andIdIn(productIdList);
        List<Product> productList = productMapper.selectByExample(productExample);

        if (productList.size() == 0) {
            return result;
        }

        list.stream().forEach(item -> {
            UsersInfo usersInfo = usersInfoList.stream().filter(s -> s.getId().equals(item.getUserId())).collect(Collectors.toList()).get(0);
            Users users = usersMapper.selectByPrimaryKey(usersInfo.getId());
            PlatformStrictInfoResponse response = new PlatformStrictInfoResponse();
            BeanUtils.copyProperties(item, response);
            response.setHeadImg(usersInfo.getHeadImg());
            response.setUserId(users.getId());
            response.setUserName(users.getNickname());
            List<Product> products = productList.stream().filter(s -> s.getId().equals(item.getProductId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(products)) {
                response.setProductName("");
            }else {
                Product product = products.get(0);
                response.setProductName(product.getProductName());
            }
            if (StringUtils.isEmpty(item.getPollContent())) {
                response.setPollList(new ArrayList<>());
            }else {
                response.setPollList(Arrays.asList(item.getPollContent().split("\\|")));
            }
            result.add(response);
        });
        return result;
    }

    /**
     * 查询达人收益，这里得按日、周和累计来获取
     */
    @Override
    public PlatformStrictProfitResponse incomeInfo(Integer userId, Integer type) {
        String s = redisService.get("talent:incomeInfo:" + userId);
        PlatformStrictProfitResponse platformStrictProfitResponse = JSON.parseObject(s, PlatformStrictProfitResponse.class);
        if (null != platformStrictProfitResponse){
            return platformStrictProfitResponse;
        }
        PlatformStrictProfitResponse response = new PlatformStrictProfitResponse();
        SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy/MM/dd");
        MyIncomeDataResponse myIncomeDataResponse = null;//获取昨日和上周收益
        String redisDayIncome = redisService.get("talent:income:day:" + userId);
        if (StringUtils.isEmpty(redisDayIncome)) {
            myIncomeDataResponse = usersClient.getMyWalletRpcAndIncrease(userId);//获取昨日和上周收益
            redisService.set("talent:income:day:" + userId, JSONObject.toJSONString(myIncomeDataResponse));
            redisService.expire("talent:income:day:" + userId, 30 * 60);
        }else {
            myIncomeDataResponse = JSON.parseObject(redisDayIncome, MyIncomeDataResponse.class);
        }

        PlatformStrictProfit platformStrictProfit = platformStrictProfitMapper.selectByUserId(userId);//日数据，还差一些曝光量等

        Integer exposureNum_day = queryConsultNum(1, userId, DynamicExposureTypeEnums.EXPOSURE.getCode());//曝光量-日
        Integer exposureNum_week = queryConsultNum(2, userId, DynamicExposureTypeEnums.EXPOSURE.getCode());//曝光量-周
        Integer exposureNum_history = queryConsultNum(3, userId, DynamicExposureTypeEnums.EXPOSURE.getCode());//曝光量-历史

        Integer viewNum_day = queryConsultNum(1, userId, DynamicExposureTypeEnums.BROWSE.getCode());//浏览量-日
        Integer viewNum_week = queryConsultNum(2, userId, DynamicExposureTypeEnums.BROWSE.getCode());//浏览量-周
        Integer viewNum_history = queryConsultNum(3, userId, DynamicExposureTypeEnums.BROWSE.getCode());//浏览量-历史

        PlatformStrictProfitItemResponse itemResponse_day = generateIncomeInfoMethod(userId, 1, exposureNum_day, viewNum_day, platformStrictProfit);
        if (null != myIncomeDataResponse) {
            BigDecimal yestoryDayIncome = myIncomeDataResponse.getYestoryDay();//昨日收益
            BigDecimal curDayIncome = itemResponse_day.getIncome_day();//今日收益
            itemResponse_day.setIncrease(curDayIncome.subtract(null == yestoryDayIncome ? BigDecimal.ZERO : yestoryDayIncome));
        }
        itemResponse_day.setDaySection(sdfDay.format(new Date()));
        response.setDay(itemResponse_day);//日数据

        PlatformStrictProfitItemResponse itemResponse_week = generateIncomeInfoMethod(userId, 2, exposureNum_week, viewNum_week, platformStrictProfit);
        itemResponse_week.setDaySection(sdfDay.format(DateUtils.getTimesWeekmorning()) + "-" + sdfDay.format(DateUtils.getTimesWeeknight()));
        if (null != myIncomeDataResponse) {
            BigDecimal lasterWeekIncome = myIncomeDataResponse.getLasterWeek();//上周收益
            BigDecimal weekIncome = itemResponse_week.getIncome_day();//本周收益
            itemResponse_week.setIncrease(weekIncome.subtract(null == lasterWeekIncome ? BigDecimal.ZERO : lasterWeekIncome));
        }
        response.setWeek(itemResponse_week);//周数据

        PlatformStrictProfitItemResponse itemResponse_history = generateIncomeInfoMethod(userId, 3, exposureNum_history, viewNum_history, platformStrictProfit);
        response.setHistory(itemResponse_history);//历史数据
        AtomicReference<Integer> consultNumTotal = new AtomicReference<>(itemResponse_history.getConsultNum());// 最新累计咨询量
        String lastTimeConsultNumTotal = redisService.get("mall:user:lasttime:consultnum:" + userId);
        log.info("===consultNumTotal:{},lastTimeConsultNumTotal:{}", consultNumTotal.get(), lastTimeConsultNumTotal);
        boolean diffFlag = false;
        if (!consultNumTotal.get().equals(Integer.parseInt(StringUtils.isEmpty(lastTimeConsultNumTotal) ? "0" : lastTimeConsultNumTotal))) {//如果上次和本次不相等
            diffFlag = true;
            redisService.set("mall:user:lasttime:consultnum:" + userId, String.valueOf(consultNumTotal.get()));//设置本次累计咨询量
        }

        //获取柱形图数据
        List<PlatformStrictProfitColumnChartResponse> columnChartList = new ArrayList<>();
        String columnChartLists = redisService.get("talent:income:columnChartList:" + userId);
        if (!StringUtils.isEmpty(columnChartLists)){
            List<PlatformStrictProfitColumnChartResponse> platformStrictProfitColumnChartResponses = JSON.parseArray(columnChartLists, PlatformStrictProfitColumnChartResponse.class);
            response.setColumnChart_day(platformStrictProfitColumnChartResponses);//日收益柱形图
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
            List<DynamicIncomeDto> dynamicIncomeResultList = usersClient.queryUsersIncomeItemByUserIdAndTypeAndSource(userId, "ADD", UserBalanceSourceEnums.EVALUATION_COMMISSION.name(), 1);
            if (CollectionUtils.isEmpty(dynamicIncomeResultList)) {
                response.setColumnChart_day(new ArrayList<>());
            }else {
                dynamicIncomeResultList.stream().forEach(item -> {
                    PlatformStrictProfitColumnChartResponse columnChartResponse = new PlatformStrictProfitColumnChartResponse();
                    columnChartResponse.setDay(sdf.format(item.getCreateTime()));
                    columnChartResponse.setIncomeAmount(item.getAddAmount());
                    columnChartList.add(columnChartResponse);
                });
            }
            redisService.set("talent:income:columnChartList:" + userId, JSONObject.toJSONString(columnChartList));
            redisService.expire("talent:income:columnChartList:" + userId, 30 * 60);
            response.setColumnChart_day(columnChartList);//日收益柱形图
        }
        Calendar calendar = Calendar.getInstance();
        int weeks = calendar.getWeeksInWeekYear() - 1;//上周数

        List<PlatformStrictProfitColumnChartResponse> columnChartList_week = new ArrayList<>();
        String columnChartList_weeks = redisService.get("talent:income:columnChartList_week:" + userId);
        if (!StringUtils.isEmpty(columnChartList_weeks)) {
            List<PlatformStrictProfitColumnChartResponse> platformStrictProfitColumnChartResponses = JSON.parseArray(columnChartList_weeks, PlatformStrictProfitColumnChartResponse.class);
            response.setColumnChart_week(platformStrictProfitColumnChartResponses);//周收益柱形图
        }else {
            List<UsersBalanceRecordStatistics> columnChartWeekList = platformStrictProfitMapper.getUsersBalanceRecordWeekStaticstics(userId, weeks);
            if (CollectionUtils.isEmpty(columnChartWeekList)) {
                response.setColumnChart_week(new ArrayList<>());
            } else {
                columnChartWeekList.stream().forEach(item -> {
                    PlatformStrictProfitColumnChartResponse columnChartResponse = new PlatformStrictProfitColumnChartResponse();
                    String startDayOfWeekNo = "";
                    String endDayOfWeekNo = "";
                    try {
                        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
                        String year = sdfYear.format(item.getEndTime());
                        startDayOfWeekNo = WeekToDateUtil.getStartDayOfWeekNo(Integer.valueOf(year), item.getWeeks());
                        endDayOfWeekNo = WeekToDateUtil.getEndDayOfWeekNo(Integer.valueOf(year), item.getWeeks());
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
//                columnChartResponse.setDay(String.valueOf(item.getWeeks()));
                    columnChartResponse.setDay(startDayOfWeekNo + "-" + endDayOfWeekNo);
                    columnChartResponse.setIncomeAmount(item.getIncomeAmount());
                    columnChartList_week.add(columnChartResponse);
                });
            }
            redisService.set("talent:income:columnChartList_week:" + userId, JSONObject.toJSONString(columnChartList_week));
            redisService.expire("talent:income:columnChartList_week:" + userId, 10 * 60);
            response.setColumnChart_week(columnChartList_week);//周收益柱形图
        }
        List<PlatformStrictProfitColumnChartResponse> columnChartList_history = new ArrayList<>();
        List<UsersBalanceRecordStatistics> columnChartMonthList = platformStrictProfitMapper.getUsersBalanceRecordMonthStaticstics(userId);
        if (CollectionUtils.isEmpty(columnChartMonthList)) {
            response.setColumnChart_history(new ArrayList<>());
        }else {
            columnChartMonthList.stream().forEach(item -> {
                PlatformStrictProfitColumnChartResponse columnChartResponse = new PlatformStrictProfitColumnChartResponse();
                columnChartResponse.setDay(item.getMonths() + "月");
                columnChartResponse.setIncomeAmount(item.getIncomeAmount());
                columnChartList_history.add(columnChartResponse);
            });
        }
        response.setColumnChart_history(columnChartList_history);

        //获取收益详情数据
        List<Dynamic> dynamicList = dynamicService.getDynamicIdsByUserId(userId);
        if (CollectionUtils.isEmpty(dynamicList)) {
            response.setDynamicIncomeList(new ArrayList<>());
        }else {
            List<DynamicIncomeDetailResponse> dynamicIncomeDetailResponseList = new ArrayList<>();
            boolean finalDiffFlag = diffFlag;
            Random random = new Random();

            AtomicReference<Integer> balanceNum = consultNumTotal;
            int forNum = dynamicList.size();
            AtomicInteger forNum_ = new AtomicInteger(0);
            dynamicList.stream().forEach(item -> {
                DynamicIncomeDetailResponse dynamicIncomeDetailResponse = new DynamicIncomeDetailResponse();
                dynamicIncomeDetailResponse.setProductName(item.getProductName());
                //订单量
                dynamicIncomeDetailResponse.setOrderNum(calculationOrderNum(item.getId()));
                //收益额
                if (null == dynamicIncomeDetailResponse.getOrderNum() || dynamicIncomeDetailResponse.getOrderNum() == 0) {
                    dynamicIncomeDetailResponse.setIncomeAmount(BigDecimal.ZERO);
                }else {
                    dynamicIncomeDetailResponse.setIncomeAmount(calculationIncomeAmount(item, dynamicIncomeDetailResponse.getOrderNum()));
                }
                try {
                    //曝光量用咨询量来代替
                    log.info("===balanceNum.get()==={}", balanceNum.get());
                    if (finalDiffFlag && null != balanceNum.get() && !balanceNum.get().equals(0)) {
                        if (1 == balanceNum.get()) {
                            redisService.set("mall:user:lasttime:dynamic:consultnum:" + item.getId(), "1");
                            dynamicIncomeDetailResponse.setExposureNum(1);
                            balanceNum.set(0);
                        }else {
                            Integer distributionNum = random.nextInt(balanceNum.get());
                            if (distributionNum.equals(0)) {
                                distributionNum = 1;
                            }
                            if (forNum_.get() + 1 == forNum) {
                                distributionNum = consultNumTotal.get();
                            }
                            balanceNum.set(consultNumTotal.get() - distributionNum);
                            redisService.set("mall:user:lasttime:dynamic:consultnum:" + item.getId(), String.valueOf(distributionNum));
                            dynamicIncomeDetailResponse.setExposureNum(distributionNum);
                        }
                    }else {
                        if (null != balanceNum.get() && balanceNum.get().equals(0)) {
                            redisService.set("mall:user:lasttime:dynamic:consultnum:" + item.getId(), "0");
                            dynamicIncomeDetailResponse.setExposureNum(0);
                        }else {
                            String lastNumStr = redisService.get("mall:user:lasttime:dynamic:consultnum:" + item.getId());
                            Integer lastNum = Integer.parseInt(StringUtils.isEmpty(lastNumStr) ? "0" : lastNumStr);
                            dynamicIncomeDetailResponse.setExposureNum(lastNum);
                        }
                    }
                    //曝光量
//                    dynamicIncomeDetailResponse.setExposureNum(calculationExposure(item.getId()));
                } catch (Exception e) {
                    log.info("======曝光量获取异常====={}", e);
                }
                dynamicIncomeDetailResponseList.add(dynamicIncomeDetailResponse);
                forNum_.addAndGet(1);
            });
            response.setDynamicIncomeList(dynamicIncomeDetailResponseList);
        }
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria().andUserIdEqualTo(userId).andOrderStatusEqualTo("3");
        List<Orders> ordersList = ordersMapper.selectByExample(ordersExample);
        //查询用户状态 1-新用户 2-已购买商品 3-已发布测评
        if (!CollectionUtils.isEmpty(dynamicList) && !CollectionUtils.isEmpty(ordersList)){
            response.setUserStatus(3);
        }else if (CollectionUtils.isEmpty(dynamicList) && !CollectionUtils.isEmpty(ordersList)){
            response.setUserStatus(2);
        }else {
            response.setUserStatus(1);
        }
        LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
        int hour = ldt.getHour();
        if (hour < 8) {
            response.setNextFlushTime("8点");
        }else if (hour > 8 && hour < 12) {
            response.setNextFlushTime("12点");
        }else if (hour > 12 && hour < 18) {
            response.setNextFlushTime("18点");
        }else if (hour > 18 && hour < 20) {
            response.setNextFlushTime("20点");
        }else {
            response.setNextFlushTime("8点");
        }
        redisService.set("talent:incomeInfo:" + userId, JSONObject.toJSONString(response));
        redisService.expire("talent:incomeInfo:" + userId, 5 * 60);
        return response;
    }

    private PlatformStrictProfitItemResponse generateIncomeInfoMethod(Integer userId, Integer type, Integer exposureNum, Integer viewNum, PlatformStrictProfit platformStrictProfit) {
        MyWalletResponse walletResponse_week = usersClient.getMyWalletRpcAndType(userId, type);//根据type查询测评收益
        PlatformStrictProfitItemResponse itemResponse_week = new PlatformStrictProfitItemResponse();
        itemResponse_week.setIncome_day(walletResponse_week.getEvaluationAmount());//周收益  需要计算日收益
        if (1 == type) {
            itemResponse_week.setIncomeRank(null == platformStrictProfit ? 0 : platformStrictProfit.getIncomeRank());//收益排行
        } else if (2 == type){
            Calendar calendar = Calendar.getInstance();
            int weeks = calendar.getWeeksInWeekYear();
//            List<UsersBalanceRecordStatistics> dynamicIncomeList = platformStrictProfitMapper.selectAllUsersWeekDynamicIncome(weeks);
            UsersBalanceRecordStatistics userBalanceSum = platformStrictProfitMapper.getUserBalanceSumByUserIdAndTime(userId, DateUtils.getTimesWeekmorning(), DateUtils.getTimesWeeknight());
            if (null == userBalanceSum) {
                itemResponse_week.setIncomeRank(1);
            }else {
                BigDecimal rankResult = userBalanceSum.getIncomeAmount().divide(new BigDecimal(incomeRankWeekBaseValue), 4, BigDecimal.ROUND_HALF_UP);
                itemResponse_week.setIncomeRank(rankResult.multiply(new BigDecimal("100")).intValue());
                if (itemResponse_week.getIncomeRank() < 1) {
                    itemResponse_week.setIncomeRank(1);
                } else if (itemResponse_week.getIncomeRank() > 99) {
                    itemResponse_week.setIncomeRank(99);
                }
            }
//            if (CollectionUtils.isEmpty(dynamicIncomeList)) {
//                itemResponse_week.setIncomeRank(1);
//            }else {
//                UsersInfoExample usersInfoExample = new UsersInfoExample();
//                usersInfoExample.createCriteria().andIsQualityEqualTo(1);
//                List<UsersInfo> usersInfoList = usersInfoMapper.selectByExample(usersInfoExample);
//                usersInfoList.stream().forEach(item -> {
//                    for (int i = 0; i < dynamicIncomeList.size(); i++) {
//                        if (item.getId().equals(dynamicIncomeList.get(i).getUserId())) {
//                            if (0 == i) {
//                                itemResponse_week.setIncomeRank(99);
//                            }else if (i == dynamicIncomeList.size() - 1) {
//                                itemResponse_week.setIncomeRank(1);
//                            }else {
//                                BigDecimal rank = new BigDecimal(i).divide(new BigDecimal(dynamicIncomeList.size()), 2, RoundingMode.HALF_UP);
//                                itemResponse_week.setIncomeRank(new BigDecimal(1).subtract(rank).multiply(new BigDecimal(100)).intValue());
//                            }
//                        }else {
//                            itemResponse_week.setIncomeRank(1);
//                        }
//                    }
//                });
//            }
        } else if (3 == type) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            int curMonth = Integer.parseInt(sdf.format(date));
//            List<UsersBalanceRecordStatistics> dynamicIncomeList = platformStrictProfitMapper.selectAllUsersMonthDynamicIncome(curMonth);
            UsersBalanceRecordStatistics usersBalanceRecordStatistics = platformStrictProfitMapper.selectAllUsersHistoryDynamicIncome(userId);
            if (null == usersBalanceRecordStatistics) {
                itemResponse_week.setIncomeRank(1);
            }else {
                BigDecimal rankResult = usersBalanceRecordStatistics.getIncomeAmount().divide(new BigDecimal(incomeRankHistoryBaseValue), 4, BigDecimal.ROUND_HALF_UP);
                itemResponse_week.setIncomeRank(rankResult.multiply(new BigDecimal("100")).intValue());
                if (itemResponse_week.getIncomeRank() < 1) {
                    itemResponse_week.setIncomeRank(1);
                } else if (itemResponse_week.getIncomeRank() > 99) {
                    itemResponse_week.setIncomeRank(99);
                }
            }
        }
        BigDecimal browseRatio_week = BigDecimal.ZERO;
        log.info("===viewNum={},exposureNum={}", viewNum, exposureNum);
        if (0 != viewNum && BigDecimal.valueOf(viewNum).compareTo(BigDecimal.ZERO) != 0 && BigDecimal.valueOf(exposureNum).compareTo(BigDecimal.ZERO) != 0) {
            log.info("=====if======");
            browseRatio_week = BigDecimal.valueOf(viewNum).divide(BigDecimal.valueOf(exposureNum),2,RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        log.info("===browseRatio_week==={}", browseRatio_week);
        itemResponse_week.setBrowseRatio(browseRatio_week.multiply(new BigDecimal(100)));//浏览转化率 = 曝光量 / 浏览量
        itemResponse_week.setExposureNumDay(exposureNum);//曝光量
        itemResponse_week.setBrowseNumDay(viewNum);//浏览量
        Integer consultNum_week = queryConsultNum(type, userId, DynamicExposureTypeEnums.URORA.getCode());//咨询量
        Integer orderNum_week = orderNumByUsersId(userId, type);//订单量
        if (null == consultNum_week || 0 == consultNum_week) {
            itemResponse_week.setOrderRatio(new BigDecimal("100"));//订单转化率= 订单量 / 咨询量
        } else {
            itemResponse_week.setOrderRatio(BigDecimal.valueOf(orderNum_week).divide(BigDecimal.valueOf(consultNum_week),2,RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")));
        }
        itemResponse_week.setConsultNum(consultNum_week);//咨询量
        itemResponse_week.setOrderNum(orderNum_week);//订单量
        return itemResponse_week;
    }

    /**
     * 查询咨询量
     * @param type 1-天 2-周 3-累计
     * @param userId 用户id
     * @param valueType 类别 1-曝光量 2-浏览量 3-日收益 4-咨询量
     * @return
     */
    private Integer queryConsultNum(Integer type, Integer userId, Integer valueType) {
        DynamicExposureRecordExample exposureRecordExample = new DynamicExposureRecordExample();
        DynamicExposureRecordExample.Criteria criteria = exposureRecordExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andTypeEqualTo(valueType.byteValue());
        if (1 == type) {
            exposureRecordExample.setOrderByClause("create_time desc limit 1");
        } else if (2 == type) {
//            Map<String, Object> upWeek = DateUtils.upWeek();
            Date monday = DateUtils.getTimesWeekmorning();
//            Timestamp weekStart = monday;
            Date curDay = new Date();
            criteria.andCreateTimeBetween(monday, curDay);
            exposureRecordExample.setOrderByClause("create_time desc");
        } else if (3 == type) {
            exposureRecordExample.setOrderByClause("create_time desc");
        }
        List<DynamicExposureRecord> list = dynamicExposureRecordMapper.selectByExample(exposureRecordExample);
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        if(1 == type){
            DynamicExposureRecord record = list.get(0);
            return (null == record.getTaskValue() ? 0 : record.getTaskValue()) + (null == record.getSupportValue() ? 0 : record.getSupportValue());
        }else {
            AtomicReference<Integer> num = new AtomicReference<>(0);
            list.forEach(item ->{
                num.set((null == item.getTaskValue() ? 0 : item.getTaskValue()) + (null == item.getSupportValue() ? 0 : item.getSupportValue()) + num.get());
            });
            return num.get();
        }
    }

    /**
     * 每条动态的总收益额
     * @param dynamic
     * @param orderNum
     * @return
     */
    private BigDecimal calculationIncomeAmount(Dynamic dynamic, Integer orderNum) {
        BigDecimal productPrice = dynamic.getProdcutPrice();//商品售价
        BigDecimal brokerage = productPrice.multiply(new BigDecimal(brokerageRatio))
                .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
        return brokerage.multiply(BigDecimal.valueOf(orderNum));
    }

    /**
     * 每条动态的曝光量
     * @param id
     * @return
     */
    private int calculationExposure(Integer id) {
        ExposureNumResponse res = adminClient.sumExposureByDynamicId(id);
        if (null == res && null == res.getExposureNum()){
            return 0;
        }
        return null == res.getExposureNum() ? 0 : res.getExposureNum();
    }

    /**
     * 获取测评下的订单量
     * @param id
     * @return
     */
    private int calculationOrderNum(Integer id) {
        return ordersService.queryOrderNumByDynamicId(Arrays.asList(id), 3);
    }

    /**
     * 获取通过用户的测评购买的订单
     * @param userId
     * @param type 1-按天获取  2-按周获取  3-历史量
     * @return
     */
    private Integer orderNumByUsersId(Integer userId, Integer type) {
        List<Dynamic> dynamicList = dynamicService.getDynamicIdsByUserId(userId);
        if (CollectionUtils.isEmpty(dynamicList)) {
            return 0;
        }
        List<Integer> dynamicIds = dynamicList.stream().map(Dynamic::getId).collect(Collectors.toList());
        Integer orderNum = ordersService.queryOrderNumByDynamicId(dynamicIds, type);
        return orderNum;
    }

    /**
     *  严选官主页-获取严选官榜单排名
     * @return
     */
    @Override
    public List<PlatformStrictListResponse> getListRanking(Integer id) {

        UsersResponse currentUser = null;
        Integer userId = null;
        try {
            currentUser = this.getCurrentUser();
            userId = currentUser.getId();
        } catch (Exception e) {
            log.info("=====用户未登陆=====");
            e.printStackTrace();
        }
        PlatformStrictListExample platformStrictListExample = new PlatformStrictListExample();
        if (null != id){
            platformStrictListExample.createCriteria().andIdEqualTo(id);
        }
        platformStrictListExample.setOrderByClause("list_sort asc");
        List<PlatformStrictList> platformStrictLists = platformStrictListMapper.selectByExample(platformStrictListExample);
        List<PlatformStrictListResponse> responses = new ArrayList<>();
        platformStrictLists.stream().sorted(Comparator.comparing(PlatformStrictList :: getType)).forEach(item ->{
            PlatformStrictListResponse response = new PlatformStrictListResponse();
            response.setId(item.getId());
            response.setCreateTime(item.getCreateTime());
            response.setListSort(item.getListSort());
            response.setListType(item.getListType());
            response.setType(item.getType());
            responses.add(response);
        });
        Integer finalAdmin = userId;
        responses.stream().forEach(item ->{
            List<AppPlatformStrictResp> appPlatformStricts = appPlatformStrictMapper.selectByListId(item.getId());
            if (null != id && null != finalAdmin){
                appPlatformStricts.stream().forEach(user -> {
                    // 是否关注他人
                    Integer isAttention = usersClient.isAttention(finalAdmin, user.getUserId());
                    user.setIsFollow(isAttention == 1 ? true : false);
                });
            }
            item.setPlatformStrictList(appPlatformStricts);
        });
        return responses;
    }

    @Override
    public LeadPlaceAnOrderResponse guidePlaceAnOrder() {
        LeadPlaceAnOrderResponse response = new LeadPlaceAnOrderResponse();
        int i = 0;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            Date beforeDate = simpleDateFormat.parse(talentUplineTime);
            i = DateUtils.differentDaysByMillisecond(beforeDate, new Date());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        response.setBonus((long) (2492000 + i * 44500));
        List<UsersResp> usersRespList = new ArrayList<>();
        List<UsersResponse> usersResponses = usersMapper.selectRandom();
        usersResponses.forEach(item -> {
            UsersResp usersResp = new UsersResp();
            usersResp.setUserId(item.getId());
            usersResp.setUserName(item.getNickname());
            usersResp.setHeadImg(item.getHeadImg());
            int[] temp = {2000, 500, 400, 50};
            int index = (int) (Math.random() * temp.length);
            usersResp.setPartitionMoney(temp[index]);
            usersRespList.add(usersResp);
        });
        response.setUsersResponses(usersRespList);
        return response;
    }

    /**
     * 随机展示5个优质测评
     */
    @Override
    public CommonResult getFiveSuperiorDynamic() {
        return dynamicService.getFiveSuperiorDynamic();
    }
}
